package com.heng.threadLocalDemo;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class House{
    int saleCount = 0;
    public synchronized void saleHouse() {
        ++saleCount;
    }
    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(()->0);
    public void saleVolumeByThreadLocal() {

        saleVolume.set(1+saleVolume.get());
    }
}

public class ThreadLocalDemo01 {
    public static void main(String[] args) {
        House house = new House();

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                try {
                    int size = new Random().nextInt(5) + 1;
                    for (int j = 0; j < size; j++) {
                        house.saleHouse();
                        house.saleVolumeByThreadLocal();//存储每个线程的销售数量
                    }
                    System.out.println(Thread.currentThread().getName()+"\t 号售卖出："+house.saleVolume.get());
                }finally {
                    house.saleVolume.remove();
                }
            },String.valueOf(i)).start();
        }
        try {TimeUnit.SECONDS.sleep(1);}catch (InterruptedException e) {e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() +"\t"+house.saleCount);
    }
}
